package com.xinghanlaser.applet.base.common.annotation;


import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author grandpa
 * @date 2023/3/20 14:25
 * @describe 枚举校验注解实现类
 */
public class EnumValidator implements ConstraintValidator<EnumValidated, Object> {

    /**
     * 枚举的值
     */
    private final List<Object> values = new ArrayList<>();

    @Override
    public void initialize(EnumValidated constraintAnnotation) {
        Class<?> enumClazz = constraintAnnotation.value();
        Object[] enumConstants = enumClazz.getEnumConstants();
        if (null == enumConstants) {
            return;
        }
        Method method;
        try {
            method = enumClazz.getMethod(constraintAnnotation.method());
        } catch (Exception e) {
            throw new RuntimeException("枚举未找到方法"+constraintAnnotation.method(), e);
        }

        method.setAccessible(true);
        try {
            for (Object enumConstant : enumConstants) {
                values.add(method.invoke(enumConstant));
            }
        } catch (Exception e) {
            throw new RuntimeException("获取枚举值失败", e);
        }
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        return null == value || values.contains(value);
    }
}